import { Injectable } from '@nestjs/common';
import { CreateCodeSnippetDto } from './dto/create-code-snippet.dto';
import { UpdateCodeSnippetDto } from './dto/update-code-snippet.dto';
import { Repository, Like } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CodeSnippet } from './entities/code-snippet.entity'

@Injectable()
export class CodeSnippetService {
    constructor(@InjectRepository(CodeSnippet) private readonly codeSnippet: Repository<CodeSnippet>) { }
    create(createCodeSnippetDto: CreateCodeSnippetDto) {
        const data = new CodeSnippet()
        data.content = createCodeSnippetDto.content
        data.desc = createCodeSnippetDto.desc
        return this.codeSnippet.save(data)
    }

    async findAll(query: { keyword: string, pageNo: number, pageSize: number }) {
        const records = await this.codeSnippet.find({
            where: [
                { content: Like(`%${query.keyword}%`) },
                { desc: Like(`%${query.keyword}%`) },
            ],
            order: {
                id: "DESC"
            },
            skip: (query.pageNo - 1) * query.pageSize,
            take: query.pageSize,
        })
        const total = await this.codeSnippet.count({
            where: [
                { content: Like(`%${query.keyword}%`) },
                { desc: Like(`%${query.keyword}%`) },
            ],
        })
        return {
            records,
            total
        }
    }

    update(id: number, updateCodeSnippetDto: UpdateCodeSnippetDto) {
        return this.codeSnippet.update(id, updateCodeSnippetDto)
    }

    remove(id: number) {
        return this.codeSnippet.delete(id)
    }

    findOne(id: number) {
        return `This action returns a #${id} codeSnippet`;
    }
}
